/**
 * 文档管理组件
 * 负责文档上传、列表显示、删除等功能
 */
class AppMainDocument {  constructor() {
    this.uploadBtn = null;
    this.fileInput = null;
    this.refreshBtn = null;
    this.selectAllBtn = null;
    this.batchVectorizeBtn = null;
    this.deleteSelectedBtn = null;
    this.documentsCount = null;
    this.documentsList = null;
    this.emptyState = null;

    // 文档数据
    this.documents = [];
    this.selectedDocuments = new Set();

  }

  /**
   * 初始化组件
   */
  async init() {
    // 加载组件HTML内容
    await this.loadDocumentHTML();

    // 获取DOM元素
    this.bindElements();

    // 绑定事件
    this.bindEvents();

  }
  /**
   * 加载文档管理HTML内容
   */
  async loadDocumentHTML() {
    try {
      const response = await fetch('./components/app-main-document.html');
      const documentHTML = await response.text();

      // 检查文档组件是否已经存在
      const existingDocumentMain = document.querySelector('.app-main-document');
      if (existingDocumentMain) {
        return; // 已经存在，不需要重复加载
      }

      // 在header后插入文档管理组件
      const header = document.querySelector('.app-header');
      if (header) {
        header.insertAdjacentHTML('afterend', documentHTML);
      } else {
        // 如果没有header，在body中插入
        document.body.insertAdjacentHTML('beforeend', documentHTML);
      }

      // 默认隐藏文档管理组件
      const documentMain = document.querySelector('.app-main-document');
      if (documentMain) {
        documentMain.style.display = 'none';
      }
    } catch (error) {
      console.error('加载文档管理HTML失败:', error);
    }
  }  /**
   * 绑定DOM元素
   */
  bindElements() {
    this.uploadBtn = document.getElementById('upload-btn');
    this.fileInput = document.getElementById('file-input');
    this.refreshBtn = document.getElementById('refresh-documents-btn');
    this.selectAllBtn = document.getElementById('select-all-btn');
    this.batchVectorizeBtn = document.getElementById('batch-vectorize-btn');
    this.deleteSelectedBtn = document.getElementById('delete-selected-btn');
    this.documentsCount = document.getElementById('documents-count');
    this.documentsList = document.getElementById('documents-list');
    this.emptyState = document.getElementById('empty-state');
  }
  /**
   * 绑定事件监听器
   */
  bindEvents() {
    // 上传按钮点击事件
    if (this.uploadBtn) {
      this.uploadBtn.addEventListener('click', () => this.triggerFileUpload());
    }

    // 文件选择事件
    if (this.fileInput) {
      this.fileInput.addEventListener('change', (e) => this.handleFileUpload(e));
    }

    // 刷新按钮事件
    if (this.refreshBtn) {
      this.refreshBtn.addEventListener('click', () => this.refreshDocuments());
    }    // 全选按钮事件
    if (this.selectAllBtn) {
      this.selectAllBtn.addEventListener('click', () => this.toggleSelectAll());
    }

    // 批量向量化按钮事件
    if (this.batchVectorizeBtn) {
      this.batchVectorizeBtn.addEventListener('click', () => this.batchVectorizeDocuments());
    }

    // 删除选中按钮事件
    if (this.deleteSelectedBtn) {
      this.deleteSelectedBtn.addEventListener('click', () => this.deleteSelectedDocuments());
    }

    // 监听拖拽上传
    this.bindDragEvents();
  }

  /**
   * 绑定拖拽上传事件
   */
  bindDragEvents() {
    const uploadContainer = document.querySelector('.upload-container');
    if (!uploadContainer) return;

    uploadContainer.addEventListener('dragover', (e) => {
      e.preventDefault();
      uploadContainer.style.borderColor = '#1976d2';
      uploadContainer.style.backgroundColor = 'rgba(25, 118, 210, 0.1)';
    });

    uploadContainer.addEventListener('dragleave', (e) => {
      e.preventDefault();
      uploadContainer.style.borderColor = '#42a5f5';
      uploadContainer.style.backgroundColor = '';
    });

    uploadContainer.addEventListener('drop', (e) => {
      e.preventDefault();
      uploadContainer.style.borderColor = '#42a5f5';
      uploadContainer.style.backgroundColor = '';

      const files = e.dataTransfer.files;
      if (files.length > 0) {
        this.processFiles(files);
      }
    });
  }

  /**
   * 触发文件选择
   */
  triggerFileUpload() {
    if (this.fileInput) {
      this.fileInput.click();
    }
  }

  /**
   * 处理文件上传
   */
  handleFileUpload(event) {
    const files = event.target.files;
    if (files.length > 0) {
      this.processFiles(files);
    }
  }

  /**
   * 处理文件
   */
  async processFiles(files) {
    for (const file of files) {
      // 验证文件类型
      if (!this.isValidFileType(file)) {
        this.showNotification(`文件 ${file.name} 格式不支持`, 'warning');
        continue;
      }

      // 验证文件大小（限制10MB）
      if (file.size > 10 * 1024 * 1024) {
        this.showNotification(`文件 ${file.name} 过大，请选择小于10MB的文件`, 'warning');
        continue;
      }

      try {
        await this.uploadFile(file);
      } catch (error) {
        console.error('上传文件失败:', error);
        this.showNotification(`上传文件 ${file.name} 失败`, 'error');
      }
    }

    // 清空文件选择
    if (this.fileInput) {
      this.fileInput.value = '';
    }
  }

  /**
   * 验证文件类型
   */
  isValidFileType(file) {
    const allowedTypes = [
      'text/plain',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'text/markdown'
    ];

    const allowedExtensions = ['.txt', '.pdf', '.doc', '.docx', '.md'];

    return allowedTypes.includes(file.type) ||
      allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
  }
  /**
   * 上传文件
   */
  async uploadFile(file) {
    try {
      // 显示上传中状态
      this.showNotification(`正在上传文件 ${file.name}...`, 'info');

      // 调用API上传文件
      const uploadResult = await window.documentAPI.uploadFile(file);      // 转换后端返回的数据格式
      const document = {
        id: uploadResult.id,
        name: uploadResult.name,
        size: uploadResult.size,
        fileObjectName: uploadResult.fileObjectName,
        url: uploadResult.url,
        vectorState: uploadResult.vectorState || 'Initial',
        createTime: uploadResult.createTime,
        updateTime: uploadResult.updateTime
      };

      // 添加到文档列表
      this.documents.unshift(document);

      // 更新显示
      this.renderDocuments();

      // 显示成功消息
      this.showNotification(`文件 ${file.name} 上传成功`, 'success');

      // 保存到本地存储
      this.saveDocuments();

      return document;
    } catch (error) {
      console.error('上传文件失败:', error);
      this.showNotification(`上传文件 ${file.name} 失败: ${error.message}`, 'error');
      throw error;
    }  }

  /**
   * 加载文档列表
   */
  async loadDocuments() {
    try {
      // 显示加载状态
      this.showNotification('正在加载文档列表...', 'info');

      // 从后端API获取文档列表
      const documents = await window.documentAPI.listFiles();
      
      // 更新本地文档列表
      this.documents = documents || [];

      // 保存到本地存储作为缓存
      this.saveDocuments();

      // 渲染文档列表
      this.renderDocuments();

      if (this.documents.length > 0) {
        this.showNotification('文档列表加载完成', 'success');
      }
    } catch (error) {
      console.error('加载文档列表失败:', error);
      this.showNotification(`加载文档列表失败: ${error.message}`, 'error');

      // 如果API失败，尝试从本地存储加载
      try {
        const savedDocuments = localStorage.getItem('documentsList');
        if (savedDocuments) {
          this.documents = JSON.parse(savedDocuments);
          this.renderDocuments();
          this.showNotification('已加载本地缓存的文档列表', 'warning');
        }
      } catch (localError) {
        console.error('加载本地文档列表也失败:', localError);
        this.documents = [];
        this.renderDocuments();
      }
    }
  }

  /**
   * 保存文档列表
   */
  saveDocuments() {
    try {
      localStorage.setItem('documentsList', JSON.stringify(this.documents));
    } catch (error) {
      console.error('保存文档列表失败:', error);
    }
  }
  /**
   * 渲染文档列表
   */
  renderDocuments() {
    if (!this.documentsList || !this.emptyState) return;

    // 更新文档计数
    this.updateDocumentsCount();

    // 清空列表
    this.documentsList.innerHTML = '';

    if (this.documents.length === 0) {
      // 显示空状态
      this.emptyState.style.display = 'block';
      return;
    }

    // 隐藏空状态
    this.emptyState.style.display = 'none';

    // 渲染文档项
    this.documents.forEach(doc => {
      const docElement = this.createDocumentElement(doc);
      this.documentsList.appendChild(docElement);
    });
  }
  /**
   * 创建文档元素
   */
  createDocumentElement(doc) {
    const docDiv = document.createElement('div');
    docDiv.className = 'document-item';
    docDiv.innerHTML = `
      <div class="document-info">
        <div class="document-checkbox">
          <input type="checkbox" id="doc-${doc.id}" class="document-checkbox-input" 
                 onchange="appMainDocument.toggleDocumentSelection('${doc.id}', this.checked)">
          <label for="doc-${doc.id}" class="document-checkbox-label"></label>
        </div>
        <div class="document-details">
          <div class="document-name">${this.escapeHtml(doc.name)}</div>
          <div class="document-meta">
            <div class="document-size">
              📦 ${this.formatFileSize(doc.size)}
            </div>
            <div class="document-time">
              🕒 ${this.formatDate(doc.createTime)}
            </div>
            <div class="vector-status ${doc.vectorState}">
              ${this.getVectorStatusText(doc.vectorState)}
            </div>
          </div>
        </div>        <div class="document-actions">
          <button class="document-action-btn" onclick="appMainDocument.downloadDocument('${doc.id}')">
            💾 下载
          </button>
          <button class="document-action-btn vector" onclick="appMainDocument.vectorizeDocument('${doc.id}')" 
                  ${doc.vectorState === 'Successful' ? 'disabled' : ''}>
            🔄 向量化
          </button>
          <button class="document-action-btn delete" onclick="appMainDocument.deleteDocument('${doc.id}')">
            🗑️删除
          </button>
        </div>
      </div>
    `;

    return docDiv;
  }
  /**
   * 获取向量状态文本
   */
  getVectorStatusText(status) {
    const statusMap = {
      'Initial': '未向量化',
      'Successful': '向量化完成',
      'Failed': '向量化失败',
      'completed': '已完成',
      'failed': '失败'
    };
    return statusMap[status] || '未知';
  }
  /**
   * 下载文档
   */
  async downloadDocument(docId) {
    const doc = this.documents.find(d => d.id == docId);
    if (!doc) {
      this.showNotification('文档不存在', 'error');
      return;
    }

    try {
      let downloadUrl = null;

      // 如果没有URL或者URL无效，尝试从API获取
      if (!downloadUrl) {
        this.showNotification(`正在获取文件 ${doc.name} 的下载链接...`, 'info');
        downloadUrl = await window.documentAPI.getFileDownloadUrl(doc.id);
      }      // 创建下载链接
      const link = document.createElement('a');
      link.href = downloadUrl;
      // 使用name作为下载文件名
      link.download = doc.name;
      
      // 对于外部URL，可能需要设置target="_blank"
      if (!downloadUrl.startsWith('blob:')) {
        link.target = '_blank';
      }
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      this.showNotification(`开始下载 ${doc.name}`, 'success');
    } catch (error) {
      console.error('下载失败:', error);
      this.showNotification(`下载失败: ${error.message}`, 'error');
    }
  }
  /**
   * 删除文档
   */
  async deleteDocument(docId) {
    const doc = this.documents.find(d => d.id == docId);
    if (!doc) {
      this.showNotification('文档不存在', 'error');
      return;
    }

    if (confirm(`确定要删除文档"${doc.name}"吗？`)) {
      try {
        // 显示删除中状态
        this.showNotification(`正在删除文档 ${doc.name}...`, 'info');

        // 调用后端API删除文档
        const deleteResult = await window.documentAPI.deleteFileById(doc.id);

        if (deleteResult) {
          // 从列表中移除
          this.documents = this.documents.filter(d => d.id != docId);

          // 清理URL对象（如果是本地创建的blob URL）
          if (doc.url && doc.url.startsWith('blob:')) {
            URL.revokeObjectURL(doc.url);
          }

          // 更新显示
          this.renderDocuments();

          // 保存到本地存储
          this.saveDocuments();

          this.showNotification(`文档 ${doc.name} 已删除`, 'success');
        } else {
          this.showNotification(`删除文档 ${doc.name} 失败`, 'error');
        }
      } catch (error) {
        console.error('删除文档失败:', error);
        this.showNotification(`删除文档失败: ${error.message}`, 'error');
      }
    }
  }
  /**
   * 刷新文档列表
   */
  async refreshDocuments() {
    // 重新加载文档列表
    await this.loadDocuments();
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B';

    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  /**
   * 格式化日期
   */
  formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  /**
   * HTML转义
   */
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  /**
   * 显示通知
   */
  showNotification(message, type = 'info') {
    // 使用全局通知函数
    if (typeof window.showNotification === 'function') {
      window.showNotification(message, type);
    } else {
      console.log(`[${type.toUpperCase()}] ${message}`);
    }
  }

  /**
   * 获取文档列表
   */
  getDocuments() {
    return this.documents;
  }

  /**
   * 显示文档管理组件
   */
  show() {
    const mainElement = document.querySelector('.app-main-document');
    if (mainElement) {
      mainElement.style.display = 'flex';
      // 加载文档列表
      this.loadDocuments();
    }
  }

  /**
   * 隐藏文档管理组件
   */
  hide() {
    const mainElement = document.querySelector('.app-main-document');
    if (mainElement) {
      mainElement.style.display = 'none';
    }
  }
  /**
   * 更新文档计数
   */
  updateDocumentsCount() {
    if (this.documentsCount) {
      const total = this.documents.length;
      const selected = this.selectedDocuments.size;

      let countText = `共 ${total} 个文档`;
      if (selected > 0) {
        countText += ` (已选 ${selected} 个)`;
      }

      this.documentsCount.textContent = countText;
    }
  }
  /**
   * 切换文档选择状态
   */
  toggleDocumentSelection(docId, checked) {
    if (checked) {
      this.selectedDocuments.add(docId);
    } else {
      this.selectedDocuments.delete(docId);
    }

    this.updateDocumentsCount();
    this.updateSelectAllButton();
    this.updateDeleteSelectedButton();
    this.updateBatchVectorizeButton();
  }
  /**
   * 全选/取消全选
   */
  toggleSelectAll() {
    const checkboxes = document.querySelectorAll('.document-checkbox-input');
    const isAllSelected = this.selectedDocuments.size === this.documents.length;

    if (isAllSelected) {
      // 取消全选
      this.selectedDocuments.clear();
      checkboxes.forEach(checkbox => {
        checkbox.checked = false;
      });
      this.selectAllBtn.textContent = '📋 全选';
    } else {
      // 全选
      this.selectedDocuments.clear();
      this.documents.forEach(doc => {
        this.selectedDocuments.add(doc.id);
      });
      checkboxes.forEach(checkbox => {
        checkbox.checked = true;
      });
      this.selectAllBtn.textContent = '❌ 取消全选';
    }

    this.updateDocumentsCount();
    this.updateDeleteSelectedButton();
    this.updateBatchVectorizeButton();
  }

  /**
   * 更新全选按钮状态
   */
  updateSelectAllButton() {
    if (!this.selectAllBtn) return;

    const isAllSelected = this.selectedDocuments.size === this.documents.length && this.documents.length > 0;
    this.selectAllBtn.textContent = isAllSelected ? '❌ 取消全选' : '📋 全选';
  }
  /**
   * 更新删除选中按钮状态
   */
  updateDeleteSelectedButton() {
    if (!this.deleteSelectedBtn) return;

    if (this.selectedDocuments.size > 0) {
      this.deleteSelectedBtn.style.display = 'block';
      this.deleteSelectedBtn.textContent = `🗑️ 删除选中 (${this.selectedDocuments.size})`;
    } else {
      this.deleteSelectedBtn.style.display = 'none';
    }
  }

  /**
   * 更新批量向量化按钮状态
   */
  updateBatchVectorizeButton() {
    if (!this.batchVectorizeBtn) return;

    // 获取已选中但未向量化的文档数量
    const selectedUnvectorizedCount = [...this.selectedDocuments]
      .map(id => this.documents.find(doc => doc.id == id))
      .filter(doc => doc && doc.vectorState !== 'Successful')
      .length;

    if (this.selectedDocuments.size > 0 && selectedUnvectorizedCount > 0) {
      this.batchVectorizeBtn.style.display = 'block';
      this.batchVectorizeBtn.textContent = `⚡ 批量向量化 (${selectedUnvectorizedCount})`;
      
      // 检查是否为本地模式
      if (window.documentAPI && window.documentAPI.isLocalMode()) {
        this.batchVectorizeBtn.disabled = true;
        this.batchVectorizeBtn.title = '本地模式不支持向量化';
      } else {
        this.batchVectorizeBtn.disabled = false;
        this.batchVectorizeBtn.title = '';
      }
    } else {
      this.batchVectorizeBtn.style.display = 'none';
    }
  }
  /**
   * 删除选中的文档
   */
  async deleteSelectedDocuments() {
    if (this.selectedDocuments.size === 0) {
      this.showNotification('请先选择要删除的文档', 'warning');
      return;
    }

    const selectedCount = this.selectedDocuments.size;
    if (confirm(`确定要删除选中的 ${selectedCount} 个文档吗？`)) {
      try {
        // 显示删除中状态
        this.showNotification(`正在删除 ${selectedCount} 个文档...`, 'info');

        // 获取要删除的文档ID数组
        const selectedIds = Array.from(this.selectedDocuments);

        // 调用批量删除API
        const deleteResults = await window.documentAPI.deleteFilesByIds(selectedIds);

        // 统计删除结果
        const successCount = deleteResults.filter(result => result.success).length;
        const failCount = deleteResults.filter(result => !result.success).length;

        // 获取成功删除的文档ID
        const successIds = deleteResults
          .filter(result => result.success)
          .map(result => result.id);

        // 获取要删除的文档对象用于清理URL
        const docsToDelete = this.documents.filter(doc => successIds.includes(doc.id));

        // 清理URL对象
        docsToDelete.forEach(doc => {
          if (doc.url && doc.url.startsWith('blob:')) {
            URL.revokeObjectURL(doc.url);
          }
        });

        // 从列表中移除成功删除的文档
        this.documents = this.documents.filter(doc => !successIds.includes(doc.id));

        // 清空选择
        this.selectedDocuments.clear();

        // 更新显示
        this.renderDocuments();

        // 保存到本地存储
        this.saveDocuments();

        // 显示结果消息
        if (failCount === 0) {
          this.showNotification(`成功删除 ${successCount} 个文档`, 'success');
        } else {
          this.showNotification(`删除完成：成功 ${successCount} 个，失败 ${failCount} 个`, 'warning');
        }

        // 显示失败的详细信息
        const failedResults = deleteResults.filter(result => !result.success);
        if (failedResults.length > 0) {
          console.error('删除失败的文档:', failedResults);
        }
      } catch (error) {
        console.error('批量删除失败:', error);
        this.showNotification(`批量删除失败: ${error.message}`, 'error');
      }
    }
  }
  /**
   * 批量向量化选中的文档
   */
  async batchVectorizeDocuments() {
    // 检查是否为本地模式
    if (window.documentAPI && window.documentAPI.isLocalMode()) {
      this.showNotification('本地模式不支持文件向量化', 'warning');
      return;
    }

    if (this.selectedDocuments.size === 0) {
      this.showNotification('请先选择要向量化的文档', 'warning');
      return;
    }

    // 获取选中且未向量化的文档
    const documentsToVectorize = [...this.selectedDocuments]
      .map(id => this.documents.find(doc => doc.id == id))
      .filter(doc => doc && doc.vectorState !== 'Successful');

    if (documentsToVectorize.length === 0) {
      this.showNotification('选中的文档已全部向量化完成', 'info');
      return;
    }

    const confirmMessage = `确定要向量化 ${documentsToVectorize.length} 个文档吗？\n\n文档列表：\n${documentsToVectorize.map(doc => `• ${doc.name}`).join('\n')}`;
    
    if (!confirm(confirmMessage)) {
      return;
    }

    // 禁用批量向量化按钮
    if (this.batchVectorizeBtn) {
      this.batchVectorizeBtn.disabled = true;
      this.batchVectorizeBtn.textContent = '⚡ 向量化中...';
    }

    let successCount = 0;
    let failedCount = 0;
    const failedDocuments = [];

    try {
      this.showNotification(`开始批量向量化 ${documentsToVectorize.length} 个文档...`, 'info');

      // 逐个向量化文档
      for (const doc of documentsToVectorize) {
        try {
          this.showNotification(`正在向量化文档: ${doc.name}...`, 'info');

          // 调用向量化API
          const vectorizeResult = await window.documentAPI.vectorizeFile(doc.id);

          if (vectorizeResult) {
            // 更新文档的向量化状态
            doc.vectorState = vectorizeResult.vectorState || 'Successful';
            doc.updateTime = vectorizeResult.updateTime || new Date().toISOString();
            successCount++;
          } else {
            failedCount++;
            failedDocuments.push(doc.name);
          }
        } catch (error) {
          console.error(`向量化文档 ${doc.name} 失败:`, error);
          failedCount++;
          failedDocuments.push(doc.name);
        }
      }

      // 更新显示
      this.renderDocuments();
      this.saveDocuments();

      // 显示结果通知
      if (failedCount === 0) {
        this.showNotification(`批量向量化完成！成功向量化 ${successCount} 个文档`, 'success');
      } else {
        const message = `批量向量化完成！成功: ${successCount} 个，失败: ${failedCount} 个`;
        this.showNotification(message, failedCount < successCount ? 'warning' : 'error');
        
        if (failedDocuments.length > 0) {
          console.warn('向量化失败的文档:', failedDocuments);
        }
      }

    } catch (error) {
      console.error('批量向量化失败:', error);
      this.showNotification(`批量向量化失败: ${error.message}`, 'error');
    } finally {
      // 恢复按钮状态
      this.updateBatchVectorizeButton();
    }
  }

  /**
   * 向量化文档
   */
  async vectorizeDocument(docId) {
    const doc = this.documents.find(d => d.id == docId);
    if (!doc) {
      this.showNotification('文档不存在', 'error');
      return;
    }

    // 检查是否已经向量化
    if (doc.vectorState === 'Successful') {
      this.showNotification('文档已经向量化完成', 'warning');
      return;
    }

    // 检查是否为本地模式
    if (window.documentAPI.isLocalMode()) {
      this.showNotification('本地模式不支持文件向量化', 'warning');
      return;
    }

    if (confirm(`确定要向量化文档"${doc.name}"吗？`)) {
      try {
        // 显示向量化中状态
        this.showNotification(`正在向量化文档 ${doc.name}...`, 'info');

        // 调用后端API向量化文档
        const vectorizeResult = await window.documentAPI.vectorizeFile(doc.id);

        if (vectorizeResult) {
          // 更新文档的向量化状态
          doc.vectorState = vectorizeResult.vectorState || 'Successful';
          doc.updateTime = vectorizeResult.updateTime || new Date().toISOString();

          // 更新显示
          this.renderDocuments();

          // 保存到本地存储
          this.saveDocuments();

          this.showNotification(`文档 ${doc.name} 向量化成功`, 'success');
        } else {
          this.showNotification(`向量化文档 ${doc.name} 失败`, 'error');
        }
      } catch (error) {
        console.error('向量化文档失败:', error);
        this.showNotification(`向量化文档失败: ${error.message}`, 'error');
      }
    }
  }

  /**
   * 销毁组件
   */
  destroy() {
    // 清理URL对象
    this.documents.forEach(doc => {
      if (doc.url && doc.url.startsWith('blob:')) {
        URL.revokeObjectURL(doc.url);
      }
    });
  }
}

// 导出组件类
window.AppMainDocument = AppMainDocument;
